package org.streets.wicket.markup;

import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.IAjaxCallDecorator;
import org.apache.wicket.ajax.IAjaxIndicatorAware;
import org.apache.wicket.ajax.calldecorator.AjaxCallDecorator;
import org.apache.wicket.ajax.form.AjaxFormSubmitBehavior;
import org.apache.wicket.extensions.ajax.markup.html.AjaxIndicatorAppender;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;


public abstract class AjaxIndicatingForm extends Form implements IAjaxIndicatorAware {

	private static final long serialVersionUID = 1L;
	private final AjaxIndicatorAppender _ajaxIndicatorAppender;

	public AjaxIndicatingForm(final String id) {
		this(id, new Model(null));
	}

	public AjaxIndicatingForm(final String id, final IModel model) {
		
		super(id, model);

		_ajaxIndicatorAppender = new AjaxIndicatorAppender();
		
		add(_ajaxIndicatorAppender);

		add(new AjaxFormSubmitBehavior(this, "onsubmit") {

			private static final long serialVersionUID = 1L;

			@Override
			protected void onError(final AjaxRequestTarget target) {
				AjaxIndicatingForm.this.onError(target);
			}

			@Override
			protected void onSubmit(final AjaxRequestTarget target) {
				AjaxIndicatingForm.this.onSubmit(target);
			}

			@Override
			protected IAjaxCallDecorator getAjaxCallDecorator() {
				return new AjaxCallDecorator() {

					private static final long serialVersionUID = 1L;

					@Override
					public CharSequence decorateScript(final CharSequence script) {
						return script + "return false";
					}
				};
			}

		});
	}

	public String getAjaxIndicatorMarkupId() {
		return _ajaxIndicatorAppender.getMarkupId();
	}

	protected void onError(final AjaxRequestTarget target) {
		
	}

	protected abstract void onSubmit(final AjaxRequestTarget target);
}
